<template>
  <!-- <el-layout> -->
  <el-row v-if="cart.length" class="cart">
    <el-col :span="24" class="cart-container">
      <el-row class="cart-header">
        <el-col :span="12" class="cart-title">
          全部商品{{ cart.length > 0 ? `(${cart.length})` : '' }}
        </el-col>
      </el-row>

      <!-- 顶部部统计区域 -->
      <el-row class="cart-statistics" type="flex" justify="space-between" align="middle">
        <el-col :span="1">
          <el-button type="danger" @click="handelDeleteMany">删除</el-button>
        </el-col>
        <!-- <el-col :span="2" class="cart-title">
          全部商品{{ cart.length > 0 ? `(${cart.length})` : '' }}
        </el-col> -->

        <el-col :span="6" type="flex" justify="center">
          <span>已选择 {{ selectedCount }} 件商品</span>
        </el-col>
        <el-col :span="6" type="flex" justify="center">
          <span>总计 ￥{{ totalAmount }}</span>
        </el-col>
        <el-col :span="6" type="flex" justify="end">
          <el-button type="primary" @click="handleCheckout" :disabled="selectedCount === 0">提交订单</el-button>
        </el-col>
      </el-row>

      <!-- 表 -->
      <el-table ref="table" :data="cart" row-key="cartId" stripe @selection-change="handleSelectionChange" :fit="true"
        class="cart-table" style="width: 100%; 
        margin-top: 10px">
        <!--选择列 -->
        <el-table-column type="selection" width="50" />

        <!-- 商品列 -->
        <el-table-column label="商品" min-width="300px">
          <template #default="scope">
            <div class="cart-item">
              <div class="cart-item-img-container">
                <img :src="scope.row.bookDetail.coverUrl ? scope.row.bookDetail.coverUrl : nullImageUrl" alt="商品图"
                  class="cart-item-img" @error="handleImageError" />
              </div>
              <div class="cart-item-info">
                《{{ scope.row.bookDetail.title }}》
                <p>书籍详情：{{ scope.row.bookDetail.description }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 单价列 -->
        <el-table-column label="单价" width="100">
          <template #default="scope">
            <div class="cart-price">
              ¥{{ scope.row.bookDetail.price }}
            </div>
          </template>
        </el-table-column>

        <!-- 数量列 -->
        <!-- 数量列 -->
        <el-table-column label="数量" width="160">
          <template #default="scope">
            <el-input-number v-model.number="scope.row.quantity" :min="1" :max="scope.row.bookDetail.stock || Infinity"
              size="small" @change="handleQuantityChange(scope.row)" @blur="handleBlur(scope.row)"></el-input-number>
            <span v-if="scope.row.bookDetail.stock" class="stock-info">
              [库存: {{ scope.row.bookDetail.stock }}]
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="数量" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleDecrease(scope.row)"
              :disabled="scope.row.quantity === 1">-</el-button>
            <span style="margin: 0 10px">{{ scope.row.quantity }}</span>
            <el-button size="small" @click="handleIncrease(scope.row)">+</el-button>
          </template>
        </el-table-column> -->

        <!-- 小计列 -->
        <el-table-column label="小计" width="100">
          <template #default="scope">
            ¥{{ calculateSubtotal(scope.row) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="danger" :icon="Delete" circle style="color: white;" @click="handleDelete(scope.row)" />
          </template>
        </el-table-column>
      </el-table>



    </el-col>
  </el-row>

  <el-row v-else class="cart-empty">
    <el-col>
      <el-empty description="购物车为空" :image-size="470" />
    </el-col>
  </el-row>
  <!-- </el-layout> -->
  <PaymentDialog :payWay="'购物车结算'" :selectedBookList="selectedArray" :totalAmount="totalAmount" :cartIdList="cartIdList"
    v-model:dialogVisible="centerDialogVisible" />

</template>

<script setup>
import { ref, computed, onMounted } from 'vue'


import PaymentDialog from '@/components/order/PaymentDialog.vue'
import { Delete } from '@element-plus/icons-vue';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
// 安装decimal.js库：npm install decimal.js
import { Decimal } from 'decimal.js';

// import { getBookDetail } from '@/api/book';
const userStore = useUserStore();
const cartStore = useCartStore();

const cart = ref([]);

// 处理图片加载错误

// 使用 Vite 的 URL 解析方式处理静态资源
const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;

// 处理图片加载失败事件
const handleImageError = (event) => {
  // 直接设置为默认图片
  event.target.src = defaultImageUrl;

  console.log('图片加载失败，已替换为默认图');
};

onMounted(() => {
  showCartList()
});

const showCartList = async () => {
  try {
    await cartStore.addCartList(userStore.userInfo.userId);
    cart.value = cartStore.cartList;
  } catch (error) {
    console.error("购物车数据加载失败", error);
  }
}



// 减少数量（修复后）
// const handleDecrease = async (item) => {
//   if (item.quantity > 1) {
//     item.quantity--; // 仅减1次
//     await cartStore.updateCartItem(item.cartId, item.quantity);
//   }
// };

// 增加数量（修复后）
// const handleIncrease = async (item) => {
//   item.quantity++; // 仅加1次
//   await cartStore.updateCartItem(item.cartId, item.quantity);
// };

// 数量变化时更新购物车
const handleQuantityChange = async (item) => {
  // 确保数量在合理范围内
  if (item.quantity < 1) {
    item.quantity = 1;
  }

  const stock = item.bookDetail.stock || Infinity;
  if (item.quantity > stock) {
    item.quantity = stock;
    ElMessage.warning(`已超过最大库存，数量自动调整为 ${stock}`);
  }

  // 更新购物车（防抖处理，避免频繁请求）
  clearTimeout(item.updateTimer);
  item.updateTimer = setTimeout(async () => {
    await cartStore.updateCartItem(item.cartId, item.quantity);
  }, 300);
};

// 失去焦点时再次验证
const handleBlur = (item) => {
  const stock = item.bookDetail.stock || Infinity;
  if (item.quantity > stock) {
    item.quantity = stock;
    ElMessage.warning(`库存不足，最多可购买 ${stock} 件`);
  }
};

//存储每一行的选中状态
const selectedArray = ref([]);
const handleSelectionChange = (val) => {
  // console.log("每一行的选中状态:", val);
  selectedArray.value = val;
  // console.log("选中的:", selectedArray.value);


}

// 计算已选商品数量
const selectedCount = computed(() => {
  return selectedArray.value.filter(item => item.quantity).reduce((sum, item) => sum + item.quantity, 0);
});
// 计算总计金额
// const totalAmount = computed(() => {
//   return selectedArray.value.filter(item => item.quantity).reduce((sum, item) => sum + item.bookDetail.price * item.quantity, 0);
// });


// 计算总计金额（decimal.js方案）
const totalAmount = computed(() => {
  return selectedArray.value.filter(item => item.quantity).reduce((sum, item) => {
    const price = new Decimal(item.bookDetail.price);
    const quantity = new Decimal(item.quantity);
    // 累加计算：sum + (price * quantity)
    return sum.plus(price.times(quantity));
  }, new Decimal(0)).toFixed(2);
});

//每一行的小计金额
// 每一行的小计金额（修正版）
const calculateSubtotal = (row) => {
  const price = new Decimal(row.bookDetail.price.toString());
  const quantity = new Decimal(row.quantity.toString());
  return price.times(quantity).toFixed(2);
};

// 批量删除
const handelDeleteMany = async () => {
  console.log("已经选择列表", selectedArray.value);
  const cartList = selectedArray.value.map(item => item.cartId);
  console.log("要删除的cartIds批量删除（未调用接口）", cartList);
  await cartStore.RemoveCartItemByCartIdList(cartList)
  showCartList();
};

// 删除商品(搞定)
const handleDelete = async (item) => {
  // cart.value = cart.value.filter(i => i.id !== item.id);
  console.log(item, "要删除的商品");
  await cartStore.RemoveCartItemByCartId(item.cartId)
  showCartList();
};


//弹窗相关------

const cartIdList = ref([]);
const centerDialogVisible = ref(false);
//弹窗相关------


// 结算
const handleCheckout = () => {
  if (selectedArray.value.length > 0) {
    console.log('已经选中的购物车列表：', selectedArray.value);
    //获取selectedArray的全部cartId
    cartIdList.value = selectedArray.value.map(item => item.cartId);
    console.log('已经选中的购物车列表的cartIdList:', cartIdList.value);
    centerDialogVisible.value = true;

  };

}
</script>


<style scoped lang="less">
/* --------------------- 定义全局变量 --------------------- */
@primary-color: #4a90e2;
/* 品牌色 */
@border-color: #4a90e2;
/* 边框颜色 */
@bg-light: #f6f6f6;
/* 浅背景色 */
@spacing: 15px;
/* 间距变量 */

/* --------------------- 购物车头部 --------------------- */
.cart-header {
  padding: 15px 20px;
  margin-bottom: 20px;
  // border-bottom: 1px solid @border-color;
  background-color: @bg-light;

  .cart-title {
    font-size: 20px;
    font-weight: 700;
    color: #c40000;
    // 文字阴影
    // text-shadow: 0 0px 1px rgba(0, 0, 0, 0.5);
    margin: 0;
  }
}

/* --------------------- 表格容器 --------------------- */
.cart-table {
  margin-top: 15px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0px 3px rgba(66, 66, 66, 0.3);
  /* 新增阴影 */

  /* 表头样式 */
  .el-table__header {
    background-color: @bg-light;
    // border: 1px solid @primary-color ;

    th {
      border-bottom: 2px solid @border-color;
      font-weight: 500;
      padding: 12px 16px;
      color: #0328cd;

      background-color: #961717;
    }
  }

  /* 表体样式 */
  .el-table__body {
    tr {
      &:hover {
        background-color: #f4f1f3;
        /* 鼠标悬停背景色 */
      }

      &:not(:last-child) {
        border-bottom: 1px solid @border-color;
        /* 非最后一行添加底部边框 */
      }

      .cart-item {
        display: flex;
        align-items: center;
        gap: @spacing;
        /* 使用变量 */
        padding: 12px 16px;
        /* 行内边距 */

        .cart-item-img-container {
          width: 100px;
          height: 100px;
          box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
          // background-color: palegoldenrod;
        }

        .cart-item-img {
          width: 100px;
          height: 100px;
          object-fit: contain;
          // border: 1px solid @border-color;
          // border-radius: 4px;
        }

        .cart-item-info {
          line-height: 1.5;
          color: #8a8a8a;



          p {
            color: #666;
            font-size: 14px;
            margin-top: 5px;
          }
        }



      }

      /* 单价样式 */
      .cart-price {
        // font-size: 18px;
        font-weight: 400;
        color: #ff0000;
        margin-left: auto;
        /* 右对齐 */
      }
    }
  }

  /* 操作按钮样式 */
  .el-table__cell .el-button {
    color: @primary-color;
    padding: 0 8px;
    font-size: 14px;
    color: rgb(0, 0, 0);
  }
}

/* --------------------- 空状态样式 --------------------- */
.cart-empty {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
}

/* 顶部统计区域样式 */
.cart-statistics {
  padding: 15px 20px;
  margin-top: 10px;
  border-bottom: 1px solid @border-color;

  .el-col {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-checkbox {
    margin-right: 10px;
  }

  button {
    margin-left: 10px;
    padding: 2px 10px;
    // border: 1px solid @primary-color;
  }

  span {
    margin: 0 5px;
  }
}

.stock-info {
  font-size: 12px;
  color: #999;
  margin-left: 15px;
}

/* 低库存警告 */
.stock-warning {
  color: #f56c6c;
}
</style>